<?php

namespace app\admin\controller\purchase;

use app\common\controller\Backend;
use app\common\model\goods\GoodsHouseStock;
use app\common\model\purchase\AllotGoods;
use app\common\model\Storehouse;
use app\common\model\data\Voucher;
use think\Db;
use think\Exception;

/**
 * 同价调拨单
 *
 * @icon fa fa-circle-o
 */
class Allot extends Backend
{
    
    /**
     * Allot模型对象
     * @var \app\common\model\purchase\Allot
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\purchase\Allot;

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
    public function index(){
        if ($this->request->isAjax()) {
//            $sort = input('sort');
//            $order = input('order');
//            $offset = input('offset');
//            $limit = input('limit');
            $where = [];
            if(session('admin')['storehouse_id'] != 0){
                $where['source_storehouse_id|storehouse_id'] = session('admin')['storehouse_id'];
            }
            $filter = json_decode($this->request->get('filter'),true);
            $op = json_decode($this->request->get('op'),true);

            if (isset($filter['goods_name'])){
                $gids = Db::name('goods')->where(array('title'=>array('like','%'.trim($filter['goods_name']).'%')))->field('id')->select();
                $ids = [];
                foreach ($gids as $v){
                    $ids[]= $v['id'];
                }
                $eids = Db::name('purchase_allot_goods')->where(array('goods_id'=>array('in',$ids)))->column('purchase_allot_id');
                $filter['id'] = $eids;
                $op['id'] = 'in';
                unset($filter['goods_name']);
                $this->request->get(["filter"=> json_encode($filter),'op'=>json_encode($op)]);

            }
//            $this->handlefilter();
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $rows = $this->model->where($where)->limit($offset,$limit)->order($sort,$order)->select();
            $total = $this->model->where($where)->limit($offset,$limit)->order($sort,$order)->count();

            $rows = collection($rows)->toArray();
            $houses = Storehouse::select();
            $states = $this->model->allot_status();
            foreach ($rows as $k=> $v){
                foreach ($houses as $val){
                    if($v['source_storehouse_id'] == $val['id']){
                        $rows[$k]['ysource_storehouse_id'] = $rows[$k]['source_storehouse_id'];
                        $rows[$k]['source_storehouse_id'] = $val['name'];
                    }
                    if($v['storehouse_id'] == $val['id']){
                        $rows[$k]['ystorehouse_id'] =  $rows[$k]['storehouse_id'];
                        $rows[$k]['storehouse_id'] = $val['name'];
                    }
                }
                $rows[$k]['ystatus'] = $v['status'];
                $rows[$k]['status'] = $states[$v['status']];
                $rows[$k]['astore_id'] = session('admin')['storehouse_id'];
            }
            return array(
                'rows'=>$rows,
                'total'=>$total,
            );
        }
        return $this->view->fetch();
    }
    public function add(){
        $group = Db::name('auth_group_access')->alias('a')->where(array('uid' => session('admin')['id']))->join('zax_auth_group g', 'a.group_id = g.id')->find();
        if ($this->request->isAjax()) {
            $params = input();
            if(!isset($params['row'])){
                $this->error('未选择商品');
            }
            $sdata = $params['row'];
            $goods_num = 0;
            foreach ($sdata as $v){
                if(empty($v['goods_num']) ){
                    $this->error('商品参数不足');
                }
                $goods_num+=$v['goods_num'];
            }
            if(empty($params['source_storehouse_id']) || empty($params['storehouse_id'])){
                $this->error('仓库不能为空');
            }
            $num = $this->model->where(array('createtime'=>array('>',strtotime(date('Y-m-d',time())))))->count();
            $adata = array(
                'number' =>'TD-T-'.date('Y-m-d').'-'.getnumber($num),
              'source_storehouse_id'=>$params['source_storehouse_id'],
              'storehouse_id'=>$params['storehouse_id'],
//              'actual_cost'=>$params['actual_cost'],
//              'allfare'=>$params['allfare'],
              'explain'=>$params['explain'],
              'admin_id'=>session('admin')['id'],
              'group_id'=>$group['group_id'],
              'company'=>$group['name'],
              'goods_num'=>$goods_num,
              'operator'=>session('admin')['nickname'],
            );
            Db::startTrans();
            try {
                $this->model->save($adata);
                if(!$this->model->id){
                    Db::rollback();
                    throw new Exception('添加失败');
                }
                Db::name('bill')->insert(array(
                    'storehouse_id'=>$params['storehouse_id'],
                    'bill_id'=>$this->model->id,
                    'type'=>5,
                    'admin_id'=>session('admin')['id'],
                    'group_id'=>$group['group_id'],
                    'createtime'=>time(),
                ));
                $gdata = [];
                foreach ($sdata as $k => $v) {
                    $gdata[] = array(
                        'goods_id' => $v['goods_id'],
                        'goods_num' => $v['goods_num'],
                        'remark' => $v['remark'],
                        'storehouse_id' => $adata['storehouse_id'],
                        'purchase_allot_id' => $this->model->id,
                    );
                }

                $sGoods = new AllotGoods;
                $sGoods->saveAll($gdata);
                Db::commit();
                return array(
                    'code'=>1,
                    'msg'=>'申请成功',
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
            exit;
        }
        $this->assign('admin',session('admin'));
        $this->assign('gname',$group['name']);
        $arr = explode('/',$_SERVER['REQUEST_URI']);

        $this->assign('turl', handlePrefix().'://'.$_SERVER['SERVER_NAME'].'/'.$arr[1]);
        return $this->view->fetch();
    }
    public function seach(){
        $storehouse_id = input('storehouse_id/d',0);

        $this->assign('storehouse_id',$storehouse_id);
        return $this->view->fetch();
    }
    public function detail($ids){
        $row  = $this->model->find($ids);
        if ($this->request->isAjax()) {
            $status = input('status/d',1);
            if($status == 1){
                $type = 1;
                Db::name('examine_log')->insert(array(
                    'admin_id'=>session('admin')['id'],
                    'type'=>$type,
                    'createtime'=>time(),
                    'controller'=>'purchase/allot',
                    'source_id'=>$ids,
                    'source'=>5,
                    'remark'=>'同价调拨单',
                    'number'=>isset($row['number'])?$row['number']:'',
                ));
                $res = $this->model->save(array('status'=>2),array('id'=>$ids));
                if($res){
                    $this->success('通过申请单,等待发货');
                }
            }else{
                $type = 2;
                Db::name('examine_log')->insert(array(
                    'admin_id'=>session('admin')['id'],
                    'type'=>$type,
                    'createtime'=>time(),
                    'controller'=>'purchase/allot',
                    'source_id'=>$ids,
                    'source'=>5,
                    'remark'=>'同价调拨单',
                    'number'=>isset($row['number'])?$row['number']:'',
                ));
                $res = $this->model->save(array('status'=>6),array('id'=>$ids));
                if($res){
                    $this->success('驳回成功');
                }
            }
            $this->error('异常错误');
        }
        $plist = Db::name('purchase_allot_goods')
            ->where(array('purchase_allot_id'=>$ids))
            ->field('g.id,number,place_origin,unit,specs,goods_id,goods_num,storehouse_id,title,remark')
            ->alias('pg')
            ->join('goods g','pg.goods_id = g.id')
            ->select();

//        $plist = AllotGoods::where(array('purchase_allot_id'=>$ids))->select();
        foreach ($plist as $k=>$v){
            $GoodsHouseStock = new GoodsHouseStock;
            $plist[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['goods_id'],empty(session('admin')['storehouse_id'])?$v['storehouse_id']:session('admin')['storehouse_id']);
            $plist[$k]['stock'] = $GoodsHouseStock->getstock($v['goods_id'],empty(session('admin')['storehouse_id'])?$v['storehouse_id']:session('admin')['storehouse_id']);
        }
        if(session('admin')['storehouse_id'] >0 && $row['source_storehouse_id'] != session('admin')['storehouse_id']){
            $row['status'] = 0;
        }
        $this->assign('row',$row);
        $this->assign('plist',$plist);
        return $this->view->fetch();
    }
    public function examine1($ids=null){
        $res = $this->model->save(array('status'=>2),array('id'=>$ids));
        if($res){
            $row  = $this->model->find($ids);
            $type = 1;
            Db::name('examine_log')->insert(array(
                'admin_id'=>session('admin')['id'],
                'type'=>$type,
                'createtime'=>time(),
                'controller'=>'purchase/allot',
                'source_id'=>$ids,
                'source'=>5,
                'remark'=>'同价调拨单',
                'number'=>isset($row['number'])?$row['number']:'',
            ));
            $this->success('通过申请单,等待发货');
        }
        $this->error('异常错误');
    }
    public function examine2($ids=null){
        $row  = $this->model->find($ids);
        if(empty($row)){
            $this->error('暂无数据');
        }

        if ($this->request->isAjax()) {
            $send_cost = input('send_cost/d',0);
            $params = input('row/a');

            if(empty($params['thumb']) && empty($params['remark'])){
                $this->error('至少选择一项内容输入');
            }
            $data = array(
                'image'=>$params['thumb'],
                'remark'=>$params['remark'],
                'type'=>5,
                'source_id'=>$ids,
            );
            //减少库存
            Db::startTrans();
            try {

//                $plist = Db::name('purchase_allot_goods')
//                    ->where(array('purchase_allot_id'=>$ids))
//                    ->field('g.id,number,place_origin,unit,specs,goods_id,goods_num,storehouse_id,title,remark')
//                    ->alias('pg')
//                    ->join('goods g','pg.goods_id = g.id')
//                    ->select();
                $plist = Db::name('purchase_allot_goods')->where(array('purchase_allot_id'=>$ids))->select();

                foreach ($plist as $k=>$v){
                    $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['source_storehouse_id']))->find();
                    if($hgood['stock'] == 0){
                        throw new Exception('库存为0');
                    }
                    if($hgood['stock'] < $v['goods_num']){
                        throw new Exception('库存不足');
                    }
                    Db::name('purchase_allot_goods')->where(array('id'=>$v['id']))->update(array('costPrice'=>$hgood['balance']/$hgood['stock']));

                    $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();

                    if($hgood['stock'] == $v['goods_num']){
                        $balance = 0;
                    }else{
                        $balance = $hgood['balance']-($hgood['balance']/$hgood['stock'])*$v['goods_num'];
                    }

                    Db::name('goods_stock_log')->insert(array(
                       'goods_id'=>$v['goods_id'],
                       'createtime'=>time(),
                       'number'=>$row['number'],
                       'type'=>'同价调拨单',
                        'source'=>5,
                       'type_id'=>$row['id'],
//                       'enter_num'=>$v['goods_num'],
                       'out_num'=>$v['goods_num'],
                       'before_num'=>$hgood['stock'],
                       'now_num'=>$hgood['stock']-$v['goods_num'],
                       'storehouse_id'=>$row['source_storehouse_id'],
//                       'remark'=>$v['goods_id'],
                       'controller'=>'purchase/allot',
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
                        'final_cost'=>$hgood['balance']/$hgood['stock'], //记录的金额应该是入库的加权单价
                        'bill_cost'=>($hgood['balance']/$hgood['stock'])*$v['goods_num'], //记录的金额应该是入库的采购成本
                        'balance'=>$balance, //记录的金额当前库存总额
                    ));
                    $GoodsHouseStock = new GoodsHouseStock;
                    $rr = $GoodsHouseStock->reducestock($v['goods_id'],$row['source_storehouse_id'],$v['goods_num']);
                    if(!$rr){
                        throw new Exception('库存异常');
                    }
                }

                $Voucher = new Voucher;
                $Voucher->save($data);

                $res = $this->model->save(array('status'=>3,'send_cost'=>$send_cost),array('id'=>$ids));
                if($res){
                    Db::commit();
                    return array(
                        'code'=>1,
                        'msg'=>'发货成功',
                    );
                }else{
                    throw new Exception('状态异常');
                }
//                Db::rollback();
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
            exit;
        }
//        $res = $this->model->save(array('status'=>2),array('id'=>$ids));
//        if($res){
//            $this->success('');
//        }
//        $this->error('');
        return $this->view->fetch();
    }
    public function examine3($ids=null){
        if ($this->request->isAjax()) {
            $arrive_cost = input('arrive_cost/d',0);
            $explain = input('explain','');
            Db::startTrans();
            try {
                $res = $this->model->save(array(
                    'status'=>4,
                    'explain'=>$explain,
                    'arrive_cost'=>$arrive_cost
                ),array('id'=>$ids));
                if(!$res){
                    throw new Exception('入库失败');
                }
                $params = input('row/a');
                foreach ($params as $v){
                    Db::name('purchase_allot_goods')->where(array('goods_id'=>$v['goods_id'],'purchase_allot_id'=>$ids))->update(array('remark'=>$v['remark']));
                }
                Db::commit();
                return array(
                    'code'=>1,
                    'msg'=>'入库成功'
                );
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());

            }
        }
            $row  = $this->model->find($ids);
            $plist = Db::name('purchase_allot_goods')
                ->where(array('purchase_allot_id'=>$ids))
                ->field('g.id,number,place_origin,unit,specs,goods_id,goods_num,storehouse_id,title,remark')
                ->alias('pg')
                ->join('goods g','pg.goods_id = g.id')
                ->select();
//        $plist = AllotGoods::where(array('purchase_allot_id'=>$ids))->select();
            foreach ($plist as $k=>$v){
                $GoodsHouseStock = new GoodsHouseStock;
                $plist[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['id'],empty(session('admin')['storehouse_id'])?$v['storehouse_id']:session('admin')['storehouse_id']);
                $plist[$k]['stock'] = $GoodsHouseStock->getstock($v['id'],empty(session('admin')['storehouse_id'])?$v['storehouse_id']:session('admin')['storehouse_id']);
            }
            $this->assign('row',$row);
            $this->assign('plist',$plist);
            return $this->view->fetch();
    }
    public function examine4($ids=null){
        $row  = $this->model->find($ids);
        $plist = Db::name('purchase_allot_goods')
            ->where(array('purchase_allot_id'=>$ids))
            ->field('g.id,number,place_origin,unit,specs,goods_id,goods_num,storehouse_id,title,remark,pg.id as pgid,costPrice')
            ->alias('pg')
            ->join('goods g','pg.goods_id = g.id')
            ->select();
        if ($this->request->isAjax()) {
            if($row['status'] !=4){
                $this->error('非法操作');
            }
            $arrive_cost = input('arrive_cost/d',0);
            $explain = input('explain','');
            //增加库存量
            Db::startTrans();
            try {
                foreach ($plist as $v){
                    //获取来源的成本价
//                    $goods = new \app\common\model\goods\Goods();
//                    $final_cost = $goods->getcost($v['goods_id'],$row['source_storehouse_id']);
                    $final_cost = $v['costPrice'];

                    //添加库存
                    $GoodsHouseStock = new GoodsHouseStock;
                    $res = $GoodsHouseStock->addstock($v['goods_id'],$row['storehouse_id'],$v['goods_num'],$final_cost);

                    if(empty($res)){
                        throw new Exception('库存异常');
                    }
                    $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();

                    $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
                    Db::name('goods_stock_log')->insert(array(
                        'goods_id'=>$v['goods_id'],
                        'createtime'=>time(),
                        'number'=>$row['number'],
                        'type'=>'同价调拨单',
                        'source'=>5,
                        'type_id'=>$row['id'],
                        'enter_num'=>$v['goods_num'],
//                            'out_num'=>$v['goods_num'],
                        'before_num'=>$hgood['stock']-$v['goods_num'],
                        'now_num'=>$hgood['stock'],
                        'storehouse_id'=>$row['storehouse_id'],
                        'controller'=>'purchase/allot',
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
                        'final_cost'=>$final_cost, //记录的金额应该是入库的加权单价
                        'bill_cost'=>bcmul($final_cost,$v['goods_num'],4), //记录的金额应该是入库的采购成本
                        'balance'=>$hgood['balance'], //记录的金额当前库存总额
                    ));

                }
                $params = input('row/a');
                foreach ($params as $v){
                    Db::name('purchase_allot_goods')->where(array('goods_id'=>$v['goods_id'],'purchase_allot_id'=>$ids))->update(array('remark'=>$v['remark']));
                }

                $res = $this->model->save(array(
                    'status'=>5,
                    'explain'=>$explain,
                    'arrive_cost'=>$arrive_cost
                ),array('id'=>$ids));
                if($res){
                    Db::commit();
                   return array(
                        'code'=>1,
                        'msg'=>'入库成功'
                   );
                }
                throw new Exception('入库失败');
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
            }
        }


//        $plist = AllotGoods::where(array('purchase_allot_id'=>$ids))->select();
        foreach ($plist as $k=>$v){
            $GoodsHouseStock = new GoodsHouseStock;
            $plist[$k]['xstock'] = $GoodsHouseStock->getfictstock($v['id'],$v['storehouse_id']);
            $plist[$k]['stock'] = $GoodsHouseStock->getstock($v['id'],$v['storehouse_id']);
        }
        $this->assign('row',$row);
        $this->assign('plist',$plist);
        return $this->view->fetch('examine3');
    }
//    public function examine5($ids=null){
//        $res = $this->model->save(array('status'=>6),array('id'=>$ids));
//        if($res){
//            $this->success('驳回成功');
//        }
//        $this->error('驳回失败');
//    }

    public function cancelbill($ids = null){
        $reason = input('reason');
        if(empty($reason)){
            $this->error('理由必须填写');
        }
        if(!$this->request->isAjax()){
            $this->error('非法操作');
        }
        $row = $this->model->find($ids);
        if($row['status'] == 1|| $row['status'] >5){
            $this->error('状态异常');
        }

        Db::startTrans();
        try {
            //中止本单据
            $this->model->save(array('status'=>7), array('id' => $ids));
            //所有商品状态设置0
            $DiffGoods = new AllotGoods();
            $DiffGoods->save(array('status'=>0),array('purchase_allot_id'=>$ids));

            $group = Db::name('auth_group_access')->alias('a')->where(array('uid'=>session('admin')['id']))->join('zax_auth_group g','a.group_id = g.id')->find();
            if($row['status'] == 3){//待入库
                $this->cancel1($row,$ids,$group);
            }
            if($row['status'] == 4){//待审核
                $this->cancel1($row,$ids,$group);
            }
            if($row['status'] == 5){//已完成
                $this->cancel1($row,$ids,$group);

                $this->cancel2($row,$ids,$group);
            }

            //添加中止记录
            Db::name('cancel_bill')->insert(array(
                    'reason' => $reason,
                    'source' => 5,
                    'admin_id' => session('admin')['id'],
                    'group_id' => $group['group_id'],
                    'company' => $group['name'],
                    'operator' => session('admin')['nickname'],
                    'controller' => 'purchase/allot',
                    'source_id' => $row['id'],
                'number' => isset($row['number'])?$row['number']:'',
                    'createtime' => time(),
                ));

            Db::name('examine_log')->insert(array(
                'admin_id'=>session('admin')['id'],
                'type'=>3,
                'createtime'=>time(),
                'controller'=>'purchase/allot',
                'source_id'=>$ids,
                'source'=>5,
                'remark'=>'同价调拨单',
                'number'=>isset($row['number'])?$row['number']:'',
            ));
            Db::commit();
            return array(
                'code'=>1,
                'msg'=>'成功',
            );
        }catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
    }
    protected function cancel1($row,$ids,$group){
            //增加库存
            $plist = Db::name('purchase_allot_goods')->where(array('purchase_allot_id'=>$ids))->select();

            foreach ($plist as $k=>$v){
                $GoodsHouseStock = new GoodsHouseStock;
                $rr = $GoodsHouseStock->addstock($v['goods_id'],$row['source_storehouse_id'],$v['goods_num'],$v['costPrice'],1);
                if(!$rr){
                    throw new Exception('库存异常');
                }

                $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['source_storehouse_id']))->find();
                Db::name('goods_stock_log')->insert(array(
                    'goods_id'=>$v['goods_id'],
                    'createtime'=>time(),
                    'number'=>$row['number'],
                    'type'=>'同价调拨单',
                    'source'=>5,
                    'type_id'=>$row['id'],
                   'enter_num'=>$v['goods_num'],
//                    'out_num'=>$v['goods_num'],
                    'before_num'=>$hgood['stock']-$v['goods_num'],
                    'now_num'=>$hgood['stock'],
                    'storehouse_id'=>$row['source_storehouse_id'],
                    'controller'=>'purchase/allot',
                    'admin_id'=>session('admin')['id'],
                    'group_id'=>$group['group_id'],
                    'company'=>$group['name'],
                    'operator'=>session('admin')['nickname'],
                    'final_cost'=>$hgood['balance']/$hgood['stock'], //记录的金额应该是入库的加权单价
                    'bill_cost'=>($hgood['balance']/$hgood['stock'])*$v['goods_num'], //记录的金额应该是入库的采购成本
                    'balance'=>$hgood['balance'], //记录的金额当前库存总额
                    'is_cancel'=>1,
                ));
            }
    }
    protected function cancel2($row,$ids,$group){
        $plist = Db::name('purchase_allot_goods')
            ->where(array('purchase_allot_id'=>$ids))
            ->field('g.id,number,place_origin,unit,specs,goods_id,goods_num,storehouse_id,title,remark,costPrice')
            ->alias('pg')
            ->join('goods g','pg.goods_id = g.id')
            ->select();

                foreach ($plist as $v){
                    $hgood = Db::name('goods_house_stock')->where(array('goods_id'=>$v['goods_id'],'storehouse_id'=>$row['storehouse_id']))->find();
                    if($hgood['stock'] == 0){
                        throw new Exception('库存为0');
                    }

                    if($hgood['stock'] == $v['goods_num']){
                        $balance = 0;
                    }else{
                        $balance = $hgood['balance']-bcmul($v['costPrice'],$v['goods_num'],4);
                    }
                    Db::name('goods_stock_log')->insert(array(
                        'goods_id'=>$v['goods_id'],
                        'createtime'=>time(),
                        'number'=>$row['number'],
                        'type'=>'同价调拨单',
                        'source'=>5,
                        'type_id'=>$row['id'],
//                        'enter_num'=>$v['goods_num'],
                        'out_num'=>$v['goods_num'],
                        'before_num'=>$hgood['stock'],
                        'now_num'=>$hgood['stock']-$v['goods_num'],
                        'storehouse_id'=>$row['storehouse_id'],
                        'controller'=>'purchase/allot',
                        'admin_id'=>session('admin')['id'],
                        'group_id'=>$group['group_id'],
                        'company'=>$group['name'],
                        'operator'=>session('admin')['nickname'],
                        'final_cost'=>$v['costPrice'], //记录的金额应该是入库的加权单价
                        'bill_cost'=>bcmul($v['costPrice'],$v['goods_num'],4), //记录的金额应该是入库的采购成本
                        'balance'=>$balance, //记录的金额当前库存总额
                        'is_cancel'=>1,
                    ));
                    //添加库存
                    $GoodsHouseStock = new GoodsHouseStock;
                    $res = $GoodsHouseStock->reducestock($v['goods_id'],$row['storehouse_id'],$v['goods_num'],$v['costPrice']);

                    if(empty($res)){
                        throw new Exception('库存异常');
                    }
                }
    }
    public function printing($ids){
        $row = $this->model->find($ids);
        $list = Db::name('purchase_allot_goods')
            ->field('pg.id,g.number,title,place_origin,specs,goods_num,remark,pg.goods_id,storehouse_id,unit')
            ->alias('pg')
            ->where(array('purchase_allot_id'=>$ids))
            ->join('goods g','pg.goods_id = g.id')
            ->select();

        $hrow = Db::name('storehouse')->where(array('id'=>$row['storehouse_id']))->find();
        $source_row = Db::name('storehouse')->where(array('id'=>$row['source_storehouse_id']))->find();
        $this->assign('hrow',$hrow);
        $this->assign('source_row',$source_row);
        $this->assign('row',$row);
        $this->assign('list',$list);
        return $this->view->fetch();
    }
}
